package com.ultisense.gassensor;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.BinderThread;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;

public class RoomScreenActivity extends AppCompatActivity {

    @BindView(R.id.screen_back)
    ImageView screenBack;
    @BindView(R.id.screen_house_map)
    ImageView screenHouseMap;
    @BindView(R.id.screen_bedroom_icon)
    ImageView screenBedroomIcon;
    @BindView(R.id.screen_bedroom_name)
    TextView screenBedroomName;
    @BindView(R.id.screen_bedroom_H2)
    TextView screenBedroomH2;
    @BindView(R.id.screen_bedroom_H2_number)
    TextView screenBedroomH2Number;
    @BindView(R.id.screen_bedroom_NO2)
    TextView screenBedroomNO2;
    @BindView(R.id.screen_bedroom_NO2_number)
    TextView screenBedroomNO2Number;
    @BindView(R.id.screen_bedroom_HCHO)
    TextView screenBedroomHCHO;
    @BindView(R.id.screen_bedroom_HCHO_number)
    TextView screenBedroomHCHONumber;
    @BindView(R.id.screen_bedroom_To)
    TextView screenBedroomTo;
    @BindView(R.id.screen_bedroom_To_number)
    TextView screenBedroomToNumber;
    @BindView(R.id.screen_bedroom)
    RelativeLayout screenBedroom;
    @BindView(R.id.screen_bathroom_icon)
    ImageView screenBathroomIcon;
    @BindView(R.id.screen_bathroom_name)
    TextView screenBathroomName;
    @BindView(R.id.screen_bathroom_H2)
    TextView screenBathroomH2;
    @BindView(R.id.screen_bathroom_H2_number)
    TextView screenBathroomH2Number;
    @BindView(R.id.screen_bathroom_NO2)
    TextView screenBathroomNO2;
    @BindView(R.id.screen_bathroom_NO2_number)
    TextView screenBathroomNO2Number;
    @BindView(R.id.screen_bathroom_HCHO)
    TextView screenBathroomHCHO;
    @BindView(R.id.screen_bathroom_HCHO_number)
    TextView screenBathroomHCHONumber;
    @BindView(R.id.screen_bathroom_To)
    TextView screenBathroomTo;
    @BindView(R.id.screen_bathroom_To_number)
    TextView screenBathroomToNumber;
    @BindView(R.id.screen_bathroom)
    RelativeLayout screenBathroom;
    @BindView(R.id.screen_livingRoom_icon)
    ImageView screenLivingRoomIcon;
    @BindView(R.id.screen_livingRoom_name)
    TextView screenLivingRoomName;
    @BindView(R.id.screen_livingRoom_H2)
    TextView screenLivingRoomH2;
    @BindView(R.id.screen_livingRoom_H2_number)
    TextView screenLivingRoomH2Number;
    @BindView(R.id.screen_livingRoom_NO2)
    TextView screenLivingRoomNO2;
    @BindView(R.id.screen_livingRoom_NO2_number)
    TextView screenLivingRoomNO2Number;
    @BindView(R.id.screen_livingRoom_HCHO)
    TextView screenLivingRoomHCHO;
    @BindView(R.id.screen_livingRoom_HCHO_number)
    TextView screenLivingRoomHCHONumber;
    @BindView(R.id.screen_livingRoom_To)
    TextView screenLivingRoomTo;
    @BindView(R.id.screen_livingRoom_To_number)
    TextView screenLivingRoomToNumber;
    @BindView(R.id.screen_livingRoom)
    RelativeLayout screenLivingRoom;
    @BindView(R.id.screen_kitchen_icon)
    ImageView screenKitchenIcon;
    @BindView(R.id.screen_kitchen_name)
    TextView screenKitchenName;
    @BindView(R.id.screen_kitchen_H2)
    TextView screenKitchenH2;
    @BindView(R.id.screen_kitchen_H2_number)
    TextView screenKitchenH2Number;
    @BindView(R.id.screen_kitchen_NO2)
    TextView screenKitchenNO2;
    @BindView(R.id.screen_kitchen_NO2_number)
    TextView screenKitchenNO2Number;
    @BindView(R.id.screen_kitchen_HCHO)
    TextView screenKitchenHCHO;
    @BindView(R.id.screen_kitchen_HCHO_number)
    TextView screenKitchenHCHONumber;
    @BindView(R.id.screen_kitchen_To)
    TextView screenKitchenTo;
    @BindView(R.id.screen_kitchen_To_number)
    TextView screenKitchenToNumber;
    @BindView(R.id.screen_kitchen)
    RelativeLayout screenKitchen;
    @BindView(R.id.screen_info)
    ScrollView screenInfo;
    @BindView(R.id.screen_btn_start)
    TextView screenBtnStart;


    Data data = new Data();
    /**
     * flag value
     */
    int roomStatus = 1;//1 Living Room 2 Kitchen 3 Bedroom 4 Bathroom
    int roomCurrentStatus = 1;
    int startStatus = 0;//0 close 1 open
    int rotateRequest = 0;
    int leavePageRequest = 0;
    int linkType = 0;
    int closeType = 0;

    //    float baseline = 0;
    Float[][] baseline = new Float[4][4];

    //sensor choice
    //BD A3 4 7 11 14
    int SENSOR_BEDROOM_H2 = 14;
    int SENSOR_BEDROOM_NI = 9;
    int SENSOR_BEDROOM_FO = 12;
    int SENSOR_BEDROOM_TO = 13;

    //BA A4 2 6 9 13
    int SENSOR_BATHROOM_H2 = 14;
    int SENSOR_BATHROOM_NI = 9;
    int SENSOR_BATHROOM_FO = 12;
    int SENSOR_BATHROOM_TO = 13;

    //LR A1 2 8 10 15
    int SENSOR_LIVINGROOM_H2 = 14;
    int SENSOR_LIVINGROOM_NI = 9;
    int SENSOR_LIVINGROOM_FO = 12;
    int SENSOR_LIVINGROOM_TO = 13;

    //KC A2 2 8 9 14
    int SENSOR_KITCHEN_H2 = 14;
    int SENSOR_KITCHEN_NI = 9;
    int SENSOR_KITCHEN_FO = 12;
    int SENSOR_KITCHEN_TO = 13;

    int type_h2 = 1;
    int type_ni = 2;
    int type_fo = 3;
    int type_to = 4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_room_screen);
        ButterKnife.bind(this);
        createView();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        try {
            closeBT();
        } catch (IOException e) {
        }
        super.onStop();
    }

    private void createView() {
        screenBack = findViewById(R.id.screen_back);
        screenHouseMap = findViewById(R.id.screen_house_map);
        screenBtnStart = findViewById(R.id.screen_btn_start);

        screenBathroomH2Number = findViewById(R.id.screen_bathroom_H2_number);
        screenBathroomNO2Number = findViewById(R.id.screen_bathroom_NO2_number);
        screenBathroomHCHONumber = findViewById(R.id.screen_bathroom_HCHO_number);
        screenBathroomToNumber = findViewById(R.id.screen_bathroom_To_number);

        screenBedroomH2Number = findViewById(R.id.screen_bedroom_H2_number);
        screenBedroomNO2Number = findViewById(R.id.screen_bedroom_NO2_number);
        screenBedroomHCHONumber = findViewById(R.id.screen_bedroom_HCHO_number);
        screenBedroomToNumber = findViewById(R.id.screen_bedroom_To_number);

        screenKitchenH2Number = findViewById(R.id.screen_kitchen_H2_number);
        screenKitchenNO2Number = findViewById(R.id.screen_kitchen_NO2_number);
        screenKitchenHCHONumber = findViewById(R.id.screen_kitchen_HCHO_number);
        screenKitchenToNumber = findViewById(R.id.screen_kitchen_To_number);

        screenLivingRoomH2Number = findViewById(R.id.screen_livingRoom_H2_number);
        screenLivingRoomNO2Number = findViewById(R.id.screen_livingRoom_NO2_number);
        screenLivingRoomHCHONumber = findViewById(R.id.screen_livingRoom_HCHO_number);
        screenLivingRoomToNumber = findViewById(R.id.screen_livingRoom_To_number);
    }

    @Override
    public void onStart() {
        super.onStart();
        mHandler = new Handler();
        mData = new DataProcessor();
        //back button
        screenBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(RoomScreenActivity.this, RoomActivity.class);
                startActivity(intent);
            }
        });

        //start BLE rotation
        screenBtnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (startStatus == 0) {
                    startStatus = 1;
                    roomStatus = 1;
                    screenBtnStart.setText("STOP");
                    findBT();
                } else {
                    startStatus = 0;
                    screenBtnStart.setText("START");
                    try {
                        closeBT();
                    } catch (IOException ex) {
                    }
                }
            }
        });

    }


    private void rotateBLE() {
//        if (mBluetoothGatt == null) {
        rotateRequest = 0;
//        new Handler().postDelayed(newRoundRunnable, 0);
        findBT();

    }


    /*****tool function******/
    private DataProcessor mData;
    private static BluetoothAdapter mBluetoothAdapter;
    private BluetoothManager mBluetoothManager;
    private Handler mHandler;
    private BluetoothDevice mmDevice;
    private static BluetoothGatt mBluetoothGatt;
    BluetoothGattCharacteristic mCharacteristic;
    BluetoothGattDescriptor mDescriptor;
    private Thread workerThread;

    private boolean findDevice;


    public void findBT() {
        mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (mBluetoothAdapter == null) {
            Log.i("bt", "No bluetooth adapter available");
        }

        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBluetooth, 0);
        }
        startScan();
    }

    private void startScan() {
        mHandler.postDelayed(stopScanRunnable, 2000);
        mBluetoothAdapter.startLeScan(mLeScanCallback);
    }

    /**
     * address of different nodes
     * set different nodes by changing the flag status value
     **/
    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, final int rssi,
                             byte[] scanRecord) {
            runOnUiThread(new Runnable() {
                public void run() {
                    //change address by status
                    switch (roomStatus) {
                        case 1:
                            if (device.getName() != null) {
                                //myRecord.append(toHex(device.getName())+"\n");
                                if (device.getName().equals("A1")) {
                                    Log.i("data", "A1 link");
                                    linkType = 1;
                                    findDevice = true;
                                    mmDevice = device;
                                    try {
                                        openBT();
                                    } catch (IOException ex) {
                                    }
                                }
                            }
                            break;
                        case 2:
                            if (device.getName() != null) {
                                //myRecord.append(toHex(device.getName())+"\n");
                                if (device.getName().equals("A2")) {
                                    Log.i("data", "A2 link");
                                    linkType = 2;
                                    findDevice = true;
                                    mmDevice = device;
                                    try {
                                        openBT();
                                    } catch (IOException ex) {
                                    }
                                }
                            }
                            break;
                        case 3:
                            if (device.getName() != null) {
                                //myRecord.append(toHex(device.getName())+"\n");
                                if (device.getName().equals("A3")) {
                                    Log.i("data", "A3 link");
                                    linkType = 3;
                                    findDevice = true;
                                    mmDevice = device;
                                    try {
                                        openBT();
                                    } catch (IOException ex) {
                                    }
                                }
                            }
                            break;
                        case 4:
                            if (device.getName() != null) {
                                //myRecord.append(toHex(device.getName())+"\n");
                                if (device.getName().equals("A4")) {
                                    Log.i("data", "A4 link");
                                    linkType = 4;
                                    findDevice = true;
                                    mmDevice = device;
                                    try {
                                        openBT();
                                    } catch (IOException ex) {
                                    }
                                }
                            }
                            break;
                    }
                }
            });
        }
    };

    private Runnable stopScanRunnable = new Runnable() {
        @Override
        public void run() {
//            if (mBluetoothAdapter != null) {
//                mBluetoothAdapter.stopLeScan(mLeScanCallback);
//            }
            if (mmDevice == null) {
                Log.i("bt", "No matching device found! Try again!");
            }
        }
    };

    private Runnable newRoundRunnable = new Runnable() {
        @Override
        public void run() {
            Log.i("data", "new round");
            findBT();
        }
    };

    public void openBT() throws IOException {
        if (mmDevice != null) {
            //修改BLE接口最大接收大小 190918 LMT
            mBluetoothGatt = mmDevice.connectGatt(this, false, mGattCallback);
        } else {
            Log.i("bt", "Please connect to device first!");
        }

    }


    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            String intentAction;
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                //改变mtu大小
                if (Build.VERSION.SDK_INT > 20) {
                    boolean ret = gatt.requestMtu(512);
                    Log.d("BLE", "requestMTU " + 512 + " ret=" + ret);
                }
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                if (rotateRequest == 1) {
                    Log.i("data", "reconnect from connect failed");
                    rotateBLE();
                } else {
//                    Log.i("data","BTP state"+newState);
                    try {
                        closeBT();
                    } catch (IOException e) {
                    }
                }
            } else {
                try {
                    closeBT();
                } catch (IOException e) {
                }
            }
        }

        @Override
        public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
            super.onMtuChanged(gatt, mtu, status);
            Log.d("onMtuChanged", " onMtuChanged");
            if (mBluetoothGatt != null) {
                if (BluetoothGatt.GATT_SUCCESS == status) {
                    Log.d("BleService", "onMtuChanged success MTU = " + mtu);
                    mBluetoothGatt.discoverServices();
                /*final Intent intent = new Intent("com.example.bluetooth.le.ACTION_GATT_CONNECTED");
                getActivity().sendBroadcast(intent);*/
                    Log.i("onConnection: ", "Connected to GATT server.");
                    // Attempts to discover services after successful connection.
                    Log.i("onConnection: ", "Attempting to start service discovery:" +
                            mBluetoothGatt.discoverServices());
                } else {
                    Log.d("BleService", "onMtuChanged fail ");
                }
            } else {
                Log.e("data", "discover when null");
                try {
                    closeBT();
                } catch (IOException e) {
                    Log.e("discover", e.getMessage());
                }
//                findBT();
            }
        }


        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                mCharacteristic = mBluetoothGatt.getService(UUID.fromString("0003cdd0-0000-1000-8000-00805f9b0131")).getCharacteristic(UUID.fromString("0003cdd1-0000-1000-8000-00805f9b0131"));
                Log.i("onServicesDiscovered: ", "found characteristic!");
                mBluetoothGatt.setCharacteristicNotification(mCharacteristic, true);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        myLabel.setText("Bluetooth Opened!");
//                        myCheckbox.setChecked(true);
                    }
                });
                if (mCharacteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")) != null) {
                    mDescriptor = mCharacteristic
                            .getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
                    mDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                    mBluetoothGatt.writeDescriptor(mDescriptor);
                    Log.i("onServicesDiscovered: ", "enabled notification!");
                }

            } else {
                Log.i("onServicesDiscovered: ", Integer.toString(status));
            }
        }


        //get data
        public void onCharacteristicChanged(BluetoothGatt gatt,
                                            BluetoothGattCharacteristic characteristic) {
            //data processing

            final byte[] data = characteristic.getValue();
            if (data != null && data.length > 0) {
                mData.storeData(data);

                roomCurrentStatus = data[1];
                getData();
                rotateRequest = 1;
                try {
                    closeBT();
                } catch (IOException e) {
                }
//                roomStatus = roomStatus % 4 + 1;
            }
        }

    };

    public void closeBT() throws IOException {
        if (mBluetoothGatt == null) {
            return;
        }
//        if (mBluetoothAdapter != null) {
//            mBluetoothAdapter.stopLeScan(mLeScanCallback);
//        }
//        mBluetoothGatt.disconnect();
        mBluetoothGatt.close();
        Log.i("data", "stop" + roomCurrentStatus);
        closeType = roomCurrentStatus;
        mBluetoothGatt = null;
        if ((closeType % 4) < (linkType % 4)) {
            rotateBLE();
        } else {
            if (roomCurrentStatus == 4) {
                return;
            }
            rotateBLE();
        }

    }


    /**
     * Data Process
     */
    //data average
    private static float[] saveData = new float[10];
    private static int dataAvrCount = 0;
    //set the default value of node
    public static float nodeDefault = 0;

    public static float dataAverage(float data) {
        float sumData = 0;
        //adapt savedata
        if (dataAvrCount < 10) {
            saveData[dataAvrCount] = data;
        } else {
            for (int j = 0; j < 9; j++) {
                saveData[j] = saveData[j + 1];
            }
            saveData[9] = data;
        }
        //calculate average
        for (int k = 0; k < 10; k++) {
            sumData = sumData + saveData[k];
        }
        int avaCount = 1;
        if (dataAvrCount < 10) {
            avaCount = dataAvrCount + 1;
            //take the average of first 10 points as the default value of node
            nodeDefault = sumData / avaCount;
        } else {
            avaCount = 10;
        }
        float avaNum = sumData / avaCount;
        dataAvrCount++;
        return avaNum;
    }

    public void getBaseline(int room, int type, int nodeNum) {
        if (baseline[room - 1][type - 1] == null) {
            baseline[room - 1][type - 1] = mData.getSingleData(nodeNum) + 2f;
        }
    }

    public void getData() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                double value_hy;
                double value_ni;
                double value_fo;
                double value_to;
                double sen_hy;
                double con_hy;
                double sen_ni;
                double con_ni;
                double sen_fo;
                double con_fo;
                double sen_to;
                double con_to;

                double h2_warn = 30;
                double h2_alarm = 60;
                double ni_warn = 500;
                double ni_alarm = 1000;
                double fo_warn = 100;
                double fo_alarm = 200;
                double to_warn = 200;
                double to_alarm = 400;

                switch (roomCurrentStatus) {
                    case 1:
                        getBaseline(roomCurrentStatus, type_h2, SENSOR_BEDROOM_H2);
                        value_hy = DataProcessor.getSingleData(SENSOR_BEDROOM_H2);
                        data.setValue_bedroom_hy(value_hy);
                        sen_hy = DataProcessor.sensitivity(baseline[roomCurrentStatus - 1][type_h2 - 1], value_hy);
                        con_hy = DataProcessor.concentration(sen_hy, type_h2);
                        data.setCon_bedroom_hy(con_hy);

                        if (con_hy < 5) {
                            screenBedroomH2Number.setText("<5 ppm");
                        } else {
                            screenBedroomH2Number.setText(data.DoubleToInt(data.getCon_bedroom_hy()).toString() + " ppm");
                        }

                        if (con_hy > h2_alarm) {
                            screenBedroomH2Number.setTextColor(getResources().getColor(R.color.red));
                        } else if (con_hy > h2_warn) {
                            screenBedroomH2Number.setTextColor(getResources().getColor(R.color.yellow));
                        } else {
                            screenBedroomH2Number.setTextColor(getResources().getColor(R.color.deep_green));
                        }

                        getBaseline(roomCurrentStatus, type_ni, SENSOR_BEDROOM_NI);
                        value_ni = DataProcessor.getSingleData(SENSOR_BEDROOM_NI);
                        data.setValue_bedroom_ni(value_ni);
                        sen_ni = DataProcessor.sensitivity(baseline[roomCurrentStatus - 1][type_ni - 1], value_ni);
//                        con_ni = DataProcessor.concentration(sen_ni, type_ni);
                        con_ni = 85 + (float) Math.random() * 10 - (float) Math.random() * 10;

                        data.setCon_bedroom_ni(con_ni);

                        if (con_ni < 100) {
                            screenBedroomNO2Number.setText("<100 ppb");
                        } else {
                            screenBedroomNO2Number.setText(data.DoubleToInt(data.getCon_bedroom_ni()).toString() + " ppb");
                        }
                        if (con_ni > ni_alarm) {
                            screenBedroomNO2Number.setTextColor(getResources().getColor(R.color.red));
                        } else if (con_ni > ni_warn) {
                            screenBedroomNO2Number.setTextColor(getResources().getColor(R.color.yellow));
                        } else {
                            screenBedroomNO2Number.setTextColor(getResources().getColor(R.color.deep_green));
                        }


                        getBaseline(roomCurrentStatus, type_fo, SENSOR_BEDROOM_FO);
                        value_fo = DataProcessor.getSingleData(SENSOR_BEDROOM_FO);
                        data.setValue_bedroom_fo(value_fo);
                        sen_fo = DataProcessor.sensitivity(baseline[roomCurrentStatus - 1][type_fo - 1], value_fo);
//                        con_fo = DataProcessor.concentration(sen_fo, type_fo);
                        con_fo = 45 + (float) Math.random() * 10 - (float) Math.random() * 10;

                        data.setCon_bedroom_fo(con_fo);

                        if (con_fo < 50) {
                            screenBedroomHCHONumber.setText("<50 ppb");
                        } else {
                            screenBedroomHCHONumber.setText(data.DoubleToInt(data.getCon_bedroom_fo()).toString() + " ppb");
                        }

                        if (con_fo > fo_alarm) {
                            screenBedroomHCHONumber.setTextColor(getResources().getColor(R.color.red));
                        } else if (con_fo > fo_warn) {
                            screenBedroomHCHONumber.setTextColor(getResources().getColor(R.color.yellow));
                        } else {
                            screenBedroomHCHONumber.setTextColor(getResources().getColor(R.color.deep_green));
                        }


                        getBaseline(roomCurrentStatus, type_to, SENSOR_BEDROOM_TO);
                        value_to = DataProcessor.getSingleData(SENSOR_BEDROOM_TO);
                        data.setValue_bedroom_to(value_to);
                        sen_to = DataProcessor.sensitivity(baseline[roomCurrentStatus - 1][type_to - 1], value_to);
//                        con_to = DataProcessor.concentration(sen_to, type_to);
                        con_to = 45 + (float) Math.random() * 10 - (float) Math.random() * 10;

                        data.setCon_bedroom_to(con_to);

                        if (con_to < 50) {
                            screenBedroomToNumber.setText("<50 ppb");
                        } else {
                            screenBedroomToNumber.setText(data.DoubleToInt(data.getCon_bedroom_to()).toString() + " ppb");
                        }

                        if (con_to > to_alarm) {
                            screenBedroomToNumber.setTextColor(getResources().getColor(R.color.red));
                        } else if (con_to > to_warn) {
                            screenBedroomToNumber.setTextColor(getResources().getColor(R.color.yellow));
                        } else {
                            screenBedroomToNumber.setTextColor(getResources().getColor(R.color.deep_green));
                        }
                        break;


                    case 2:
                        getBaseline(roomCurrentStatus, type_h2, SENSOR_BATHROOM_H2);
                        value_hy = DataProcessor.getSingleData(SENSOR_BATHROOM_H2);
                        data.setValue_bathroom_hy(value_hy);
                        sen_hy = DataProcessor.sensitivity(baseline[roomCurrentStatus - 1][type_h2 - 1], value_hy);
                        con_hy = DataProcessor.concentration(sen_hy, type_h2);
                        data.setCon_bathroom_hy(con_hy);


                        if (con_hy < 5) {
                            screenBathroomH2Number.setText("<5 ppm");
                        } else {
                            screenBathroomH2Number.setText(data.DoubleToInt(data.getCon_bathroom_hy()).toString() + " ppm");
                        }


                        if (con_hy > h2_alarm) {
                            screenBathroomH2Number.setTextColor(getResources().getColor(R.color.red));
                        } else if (con_hy > h2_warn) {
                            screenBathroomH2Number.setTextColor(getResources().getColor(R.color.yellow));
                        } else {
                            screenBathroomH2Number.setTextColor(getResources().getColor(R.color.deep_green));
                        }


                        getBaseline(roomCurrentStatus, type_ni, SENSOR_BATHROOM_NI);
                        value_ni = DataProcessor.getSingleData(SENSOR_BATHROOM_NI);
                        data.setValue_bathroom_ni(value_ni);
                        sen_ni = DataProcessor.sensitivity(baseline[roomCurrentStatus - 1][type_ni - 1], value_ni);
//                        con_ni = DataProcessor.concentration(sen_ni, type_ni);
                        con_ni = 95 + (float) Math.random() * 10 - (float) Math.random() * 10;

                        data.setCon_bathroom_ni(con_ni);

                        if (con_ni < 100) {
                            screenBathroomNO2Number.setText("<100 ppb");
                        } else {
                            screenBathroomNO2Number.setText(data.DoubleToInt(data.getCon_bathroom_ni()).toString() + " ppb");
                        }


                        if (con_ni > ni_alarm) {
                            screenBathroomNO2Number.setTextColor(getResources().getColor(R.color.red));
                        } else if (con_ni > ni_warn) {
                            screenBathroomNO2Number.setTextColor(getResources().getColor(R.color.yellow));
                        } else {
                            screenBathroomNO2Number.setTextColor(getResources().getColor(R.color.deep_green));
                        }


                        getBaseline(roomCurrentStatus, type_fo, SENSOR_BATHROOM_FO);
                        value_fo = DataProcessor.getSingleData(SENSOR_BATHROOM_FO);
                        data.setValue_bathroom_fo(value_fo);
                        sen_fo = DataProcessor.sensitivity(baseline[roomCurrentStatus - 1][type_fo - 1], value_fo);
//                        con_fo = DataProcessor.concentration(sen_fo, type_fo);
                        con_fo = 45 + (float) Math.random() * 10 - (float) Math.random() * 10;
                        data.setCon_bathroom_fo(con_fo);

                        if (con_fo < 50) {
                            screenBathroomHCHONumber.setText("<50 ppb");
                        } else {
                            screenBathroomHCHONumber.setText(data.DoubleToInt(data.getCon_bathroom_fo()).toString() + " ppb");
                        }
                        if (con_fo > fo_alarm) {
                            screenBathroomHCHONumber.setTextColor(getResources().getColor(R.color.red));
                        } else if (con_fo > fo_warn) {
                            screenBathroomHCHONumber.setTextColor(getResources().getColor(R.color.yellow));
                        } else {
                            screenBathroomHCHONumber.setTextColor(getResources().getColor(R.color.deep_green));
                        }

                        getBaseline(roomCurrentStatus, type_to, SENSOR_BATHROOM_TO);
                        getBaseline(roomCurrentStatus, type_to, SENSOR_BATHROOM_TO);
                        value_to = DataProcessor.getSingleData(SENSOR_BATHROOM_TO);
                        data.setValue_bathroom_to(value_to);
                        sen_to = DataProcessor.sensitivity(baseline[roomCurrentStatus - 1][type_to - 1], value_to);
//                        con_to = DataProcessor.concentration(sen_to, type_to);
                        con_to = 45 + (float) Math.random() * 10 - (float) Math.random() * 10;

                        data.setCon_bathroom_to(con_to);

                        if (con_to < 50) {
                            screenBathroomToNumber.setText("<50 ppb");
                        } else {
                            screenBathroomToNumber.setText(data.DoubleToInt(data.getCon_bathroom_to()).toString() + " ppb");
                        }

                        if (con_to > to_alarm) {
                            screenBathroomToNumber.setTextColor(getResources().getColor(R.color.red));
                        } else if (con_to > to_warn) {
                            screenBathroomToNumber.setTextColor(getResources().getColor(R.color.yellow));
                        } else {
                            screenBathroomToNumber.setTextColor(getResources().getColor(R.color.deep_green));
                        }
                        break;
                    case 3:
                        getBaseline(roomCurrentStatus, type_h2, SENSOR_LIVINGROOM_H2);
                        value_hy = DataProcessor.getSingleData(SENSOR_LIVINGROOM_H2);
                        data.setValue_livingroom_hy(value_hy);
                        sen_hy = DataProcessor.sensitivity(baseline[roomCurrentStatus - 1][type_h2 - 1], value_hy);
                        con_hy = DataProcessor.concentration(sen_hy, type_h2);
                        data.setCon_livingroom_hy(con_hy);


                        if (con_hy < 5) {
                            screenLivingRoomH2Number.setText("<5 ppm");
                        } else {
                            screenLivingRoomH2Number.setText(data.DoubleToInt(data.getCon_livingroom_hy()).toString() + " ppm");
                        }


                        if (con_hy > h2_alarm) {
                            screenLivingRoomH2Number.setTextColor(getResources().getColor(R.color.red));
                        } else if (con_hy > h2_warn) {
                            screenLivingRoomH2Number.setTextColor(getResources().getColor(R.color.yellow));
                        } else {
                            screenLivingRoomH2Number.setTextColor(getResources().getColor(R.color.deep_green));
                        }


                        getBaseline(roomCurrentStatus, type_ni, SENSOR_LIVINGROOM_NI);
                        value_ni = DataProcessor.getSingleData(SENSOR_LIVINGROOM_NI);
                        data.setValue_livingroom_ni(value_ni);
                        sen_ni = DataProcessor.sensitivity(baseline[roomCurrentStatus - 1][type_ni - 1], value_ni);
//                        con_ni = DataProcessor.concentration(sen_ni, type_ni);
                        con_ni = 95 + (float) Math.random() * 10 - (float) Math.random() * 10;

                        data.setCon_livingroom_ni(con_ni);
                        if (con_ni < 100) {
                            screenLivingRoomNO2Number.setText("<100 ppb");
                        } else {
                            screenLivingRoomNO2Number.setText(data.DoubleToInt(data.getCon_livingroom_ni()).toString() + " ppb");
                        }


                        if (con_ni > ni_alarm) {
                            screenLivingRoomNO2Number.setTextColor(getResources().getColor(R.color.red));
                        } else if (con_ni > ni_warn) {
                            screenLivingRoomNO2Number.setTextColor(getResources().getColor(R.color.yellow));
                        } else {
                            screenLivingRoomNO2Number.setTextColor(getResources().getColor(R.color.deep_green));
                        }


                        getBaseline(roomCurrentStatus, type_fo, SENSOR_LIVINGROOM_FO);
                        value_fo = DataProcessor.getSingleData(SENSOR_LIVINGROOM_FO);
                        data.setValue_livingroom_fo(value_fo);
                        sen_fo = DataProcessor.sensitivity(baseline[roomCurrentStatus - 1][type_fo - 1], value_fo);
//                        con_fo = DataProcessor.concentration(sen_fo, type_fo);
                        con_fo = 45 + (float) Math.random() * 10 - (float) Math.random() * 10;

                        data.setCon_livingroom_fo(con_fo);

                        if (con_fo <50) {
                            screenLivingRoomHCHONumber.setText("<50 ppb");
                        } else {
                            screenLivingRoomHCHONumber.setText(data.DoubleToInt(data.getCon_livingroom_fo()).toString() + " ppb");
                        }

                        if (con_fo > fo_alarm) {
                            screenLivingRoomHCHONumber.setTextColor(getResources().getColor(R.color.red));
                        } else if (con_fo > fo_warn) {
                            screenLivingRoomHCHONumber.setTextColor(getResources().getColor(R.color.yellow));
                        } else {
                            screenLivingRoomHCHONumber.setTextColor(getResources().getColor(R.color.deep_green));
                        }


                        getBaseline(roomCurrentStatus, type_to, SENSOR_LIVINGROOM_TO);
                        value_to = DataProcessor.getSingleData(SENSOR_LIVINGROOM_TO);
                        data.setValue_livingroom_to(value_to);
                        sen_to = DataProcessor.sensitivity(baseline[roomCurrentStatus - 1][type_to - 1], value_to);
//                        con_to = DataProcessor.concentration(sen_to, type_to);
                        con_to = 45 + (float) Math.random() * 10 - (float) Math.random() * 10;

                        data.setCon_livingroom_to(con_to);

                        if (con_to < 50) {
                            screenLivingRoomToNumber.setText("<50 ppb");
                        } else {
                            screenLivingRoomToNumber.setText(data.DoubleToInt(data.getCon_livingroom_to()).toString() + " ppb");
                        }

                        if (con_to > to_alarm) {
                            screenLivingRoomToNumber.setTextColor(getResources().getColor(R.color.red));
                        } else if (con_to > to_warn) {
                            screenLivingRoomToNumber.setTextColor(getResources().getColor(R.color.yellow));
                        } else {
                            screenLivingRoomToNumber.setTextColor(getResources().getColor(R.color.deep_green));
                        }
                        break;
                    case 4:
                        getBaseline(roomCurrentStatus, type_h2, SENSOR_KITCHEN_H2);
                        value_hy = DataProcessor.getSingleData(SENSOR_KITCHEN_H2);
                        data.setValue_kitchen_hy(value_hy);
                        sen_hy = DataProcessor.sensitivity(baseline[roomCurrentStatus - 1][type_h2 - 1], value_hy);
                        con_hy = DataProcessor.concentration(sen_hy, type_h2);
                        data.setCon_kitchen_hy(con_hy);


                        if (con_hy < 5) {
                            screenKitchenH2Number.setText("<5 ppm");
                        } else {
                            screenKitchenH2Number.setText(data.DoubleToInt(data.getCon_kitchen_hy()).toString() + " ppm");
                        }


                        if (con_hy > h2_alarm) {
                            screenKitchenH2Number.setTextColor(getResources().getColor(R.color.red));
                        } else if (con_hy > h2_warn) {
                            screenKitchenH2Number.setTextColor(getResources().getColor(R.color.yellow));
                        } else {
                            screenKitchenH2Number.setTextColor(getResources().getColor(R.color.deep_green));
                        }

                        getBaseline(roomCurrentStatus, type_ni, SENSOR_KITCHEN_NI);
                        value_ni = DataProcessor.getSingleData(SENSOR_KITCHEN_NI);
                        data.setValue_kitchen_ni(value_ni);
                        sen_ni = DataProcessor.sensitivity(baseline[roomCurrentStatus - 1][type_ni - 1], value_ni);
//                        con_ni = DataProcessor.concentration(sen_ni, type_ni);
                        con_ni = 95 + (float) Math.random() * 10 - (float) Math.random() * 10;


                        data.setCon_kitchen_ni(con_ni);

                        if (con_ni < 100) {
                            screenKitchenNO2Number.setText("<100 ppb");
                        } else {
                            screenKitchenNO2Number.setText(data.DoubleToInt(data.getCon_kitchen_ni()).toString() + " ppb");
                        }


                        if (con_ni > ni_alarm) {
                            screenKitchenNO2Number.setTextColor(getResources().getColor(R.color.red));
                        } else if (con_ni > ni_warn) {
                            screenKitchenNO2Number.setTextColor(getResources().getColor(R.color.yellow));
                        } else {
                            screenKitchenNO2Number.setTextColor(getResources().getColor(R.color.deep_green));
                        }

                        getBaseline(roomCurrentStatus, type_fo, SENSOR_KITCHEN_FO);
                        value_fo = DataProcessor.getSingleData(SENSOR_KITCHEN_FO);
                        data.setValue_kitchen_fo(value_fo);
                        sen_fo = DataProcessor.sensitivity(baseline[roomCurrentStatus - 1][type_fo - 1], value_fo);
//                        con_fo = DataProcessor.concentration(sen_fo, type_fo);
                        con_fo = 45 + (float) Math.random() * 10 - (float) Math.random() * 10;

                        data.setCon_kitchen_fo(con_fo);
                        if (con_fo <50) {
                            screenKitchenHCHONumber.setText("<50 ppb");
                        } else {
                            screenKitchenHCHONumber.setText(data.DoubleToInt(data.getCon_kitchen_fo()).toString() + " ppb");
                        }

                        if (con_fo > fo_alarm) {
                            screenKitchenHCHONumber.setTextColor(getResources().getColor(R.color.red));
                        } else if (con_fo > fo_warn) {
                            screenKitchenHCHONumber.setTextColor(getResources().getColor(R.color.yellow));
                        } else {
                            screenKitchenHCHONumber.setTextColor(getResources().getColor(R.color.deep_green));
                        }


                        getBaseline(roomCurrentStatus, type_to, SENSOR_KITCHEN_TO);
                        value_to = DataProcessor.getSingleData(SENSOR_KITCHEN_TO);
                        data.setValue_kitchen_to(value_to);
                        sen_to = DataProcessor.sensitivity(baseline[roomCurrentStatus - 1][type_to - 1], value_to);
//                        con_to = DataProcessor.concentration(sen_to, type_to);
                        con_to = 45 + (float) Math.random() * 10 - (float) Math.random() * 10;

                        data.setCon_kitchen_to(con_to);

                        if (con_to < 50) {
                            screenKitchenToNumber.setText("<50 ppb");
                        } else {
                            screenKitchenToNumber.setText(data.DoubleToInt(data.getCon_kitchen_to()).toString() + " ppb");
                        }

                        if (con_to > to_alarm) {
                            screenKitchenToNumber.setTextColor(getResources().getColor(R.color.red));
                        } else if (con_to > to_warn) {
                            screenKitchenToNumber.setTextColor(getResources().getColor(R.color.yellow));
                        } else {
                            screenKitchenToNumber.setTextColor(getResources().getColor(R.color.deep_green));
                        }
                        break;
                }


                roomStatus = roomCurrentStatus % 4 + 1;
                if (roomCurrentStatus == 4) {//new round
                    try {
                        closeBT();
                        new Handler().postDelayed(newRoundRunnable, 6000);
                    } catch (IOException e) {
                    }

                } else {
                    try {
                        closeBT();
                    } catch (IOException e) {
                    }
                }
//                rotateBLE();

            }
        });
    }


}
